const db = require('../core/mysql/db.js')
const ApiResponseUtil = require('../util/ApiResponseUtil.js')

// 群组 - 创建
exports.createGroup = async (req, res) => {
    const { name, members } = req.body
    const initiator = req.auth.id
    const owner = {
        uid: initiator,
        role: 'owner',
        join_at: new Date().getTime(),
        left_at: null,
        is_muted: false,
        muted_until: null,
        status: 1
    }
    groupName = req.auth.nickname + '、' + name + '的群聊'
    const groupMembers = [owner, ...members]
    const MAX_GROUPS_PER_USER = 5;

    const sqlCreate = `
        INSERT INTO groupchat 
        (initiator, name, members, create_at, update_at) 
        VALUES (?, ?, ?, now(), now())
    `

    // 查询当前用户已经创建的群组数量
    const [count] = await db.query(
        'SELECT COUNT(*) AS total FROM groupchat WHERE initiator = ?',
        [initiator]
    );
    if (count[0].total >= MAX_GROUPS_PER_USER) {
        return res.send(ApiResponseUtil.error(403, '您已达到创建群组的数量上限'));
    } else {
        const [createResult] = await db.query(sqlCreate, [initiator, groupName, JSON.stringify(groupMembers)])
        if (createResult.affectedRows < 1) return res.send(ApiResponseUtil.error(500, '创建群组失败'))
        return res.send(ApiResponseUtil.success(200, '创建群组成功'))
    }
}

// 群组 - 搜索
exports.searchGroup = async (req, res) => {
    const { name } = req.query

    const sql = 'SELECT id, name, initiator, cover, create_at, update_at FROM groupchat WHERE name LIKE ?'

    const [result] = await db.query(sql, [`%${name}%`])

    if (result.length < 1) return res.send(ApiResponseUtil.success(200, '未搜索到群组'))

    res.send(ApiResponseUtil.success(200, '搜索群组成功', result))
}

// 群组 - 加入
exports.joinGroup = async (req, res) => {
    const { id } = req.body
    const uid = req.auth.id

    const sql = `
       UPDATE groupchat SET members = JSON_ARRAY_APPEND(members, '$', JSON_OBJECT(
            'uid', ?, 
            'role', 'member', 
            'join_at', now(), 
            'left_at', null, 
            'is_muted', false, 
            'muted_until', null, 
            'status', 0
       ))
       WHERE id = ?
    `

    const result = await db.query(sql, [uid, id])

    if (result.affectedRows < 1) return res.send(ApiResponseUtil.error(500, '加入群组失败'))

    res.send(ApiResponseUtil.success(200, '加入群组成功'))
}

// 群组 - 删除
exports.delGroup = async (req, res) => {
    const { id } = req.body
    const uid = req.auth.id

    const sql = 'DELETE FROM groupchat WHERE initiator = ? AND id = ?'

    const result = await db.query(sql, [uid, id])

    if (result.affectedRows < 1) return res.send(ApiResponseUtil.error(500, '删除群组失败'))

    res.send(ApiResponseUtil.success(200, '删除群组成功'))
}

exports.addedGroup = async (req, res) => {
    const { status } = req.query
    const uid = req.auth.id 

    const sql = `
        SELECT DISTINCT gc.*
        FROM groupchat gc, JSON_TABLE(gc.members, '$[*]' 
            COLUMNS (
                uid INT PATH '$.uid',
                role VARCHAR(20) PATH '$.role',
                status INT PATH '$.status',
                join_at BIGINT PATH '$.join_at',
                left_at BIGINT PATH '$.left_at'
            )) AS members_data
        WHERE members_data.uid = ?       
        AND members_data.status = ?       
        AND (members_data.left_at IS NULL OR members_data.left_at = NULL)  
    `

    const [result] = await db.query(sql, [uid, status])

    if (result.length < 1) return res.send(ApiResponseUtil.success(200, '未加入群组', []))

    res.send(ApiResponseUtil.success(200, '群组数据获取成功', result))
}